package org.jeecg.modules.demo.homepage.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basejobserveitem.entity.BaseJobServeItem;
import org.jeecg.modules.demo.basejobserveitem.service.IBaseJobServeItemService;
import org.jeecg.modules.demo.basemembervipcoupon.service.IBaseMemberVipCouponService;
import org.jeecg.modules.demo.baseorde.entity.BaseOrder;
import org.jeecg.modules.demo.baseorde.service.IBaseOrderService;
import org.jeecg.modules.demo.baseordercommodity.entity.BaseOrderCommodity;
import org.jeecg.modules.demo.baseordercommodity.service.IBaseOrderCommodityService;
import org.jeecg.modules.demo.baseordercommoditywriteoff.service.IBaseOrderCommodityWriteoffService;
import org.jeecg.modules.demo.baseorderproject.entity.BaseOrderProject;
import org.jeecg.modules.demo.baseorderproject.service.IBaseOrderProjectService;
import org.jeecg.modules.demo.baseorderservicewriteoff.entity.BaseOrderServiceWriteoff;
import org.jeecg.modules.demo.baseorderservicewriteoff.entity.BaseOrderServiceWriteoff2;
import org.jeecg.modules.demo.baseorderservicewriteoff.service.IBaseOrderServiceWriteoffService;
import org.jeecg.modules.demo.baseorderwriteoffrecord.entity.BaseOrderWriteoffRecord;
import org.jeecg.modules.demo.baseorderwriteoffrecord.service.IBaseOrderWriteoffRecordService;
import org.jeecg.modules.demo.basepayorder.service.IBasePayOrderService;
import org.jeecg.modules.demo.basepreorder.service.IBasePreOrderService;
import org.jeecg.modules.demo.blancechangerecord.entity.BalanceChangeRecord;
import org.jeecg.modules.demo.blancechangerecord.service.IBalanceChangeRecordService;
import org.jeecg.modules.demo.commoditygroup.service.ICommodityGroupService;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.demo.homepage.service.HomePageService;
import org.jeecg.modules.demo.levelset.service.ILevelSetService;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.projectgroup.service.IProjectGroupService;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.demo.staffmanagement.service.IStaffManagementService;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.stockmember.entity.StockMember;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.viporderrecord.entity.VipOrderRecord;
import org.jeecg.modules.demo.viporderrecord.service.IVipOrderRecordService;
import org.jeecg.modules.util.DateUtils;
import org.jeecg.modules.util.HashMapEx;
import org.jeecg.modules.util.RedisUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.jeecg.modules.util.TimeCardUtils.getDateDiscrepency;

@RestController
@RequestMapping("/stat")
@Slf4j
public class StatController {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private HomePageService homePageService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private IStaffManagementService staffManagementService;
    @Autowired
    private ICommodityGroupService commodityGroupService;
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private IProjectGroupService projectGroupService;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private IBaseOrderService baseOrderService;
    @Autowired
    private IBaseOrderCommodityService baseOrderCommodityService;
    @Autowired
    private IBaseOrderProjectService baseOrderProjectService;
    @Autowired
    private IBaseOrderServiceWriteoffService baseOrderServiceWriteoffService;
    @Autowired
    private IBaseOrderCommodityWriteoffService baseOrderCommodityWriteoffService;
    @Autowired
    private IBasePreOrderService basePreOrderService;
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private ILevelSetService levelSetService;
    @Autowired
    private IBaseMemberVipCouponService baseMemberVipCouponService;
    @Autowired
    private IBaseOrderWriteoffRecordService baseOrderWriteoffRecordService;
    @Autowired
    private IBasePayOrderService basePayOrderService;
    @Autowired
    private IBaseJobServeItemService baseJobServeItemService;
    @Autowired
    private IVipOrderRecordService vipOrderRecordService;
    @Autowired
    private IBalanceChangeRecordService balanceChangeRecordService;

    private static double sumAmountIfNotNull(List<BaseOrder> saomaList) {
        double result = 0.0;
        for (BaseOrder baseOrder : saomaList) {
            Double realAmount = baseOrder.getRealAmount();
            if (realAmount != null) {
                result = result + realAmount.doubleValue();
            }
        }
        return result;
    }

    @NotNull
    private static Double getMapValueSum(List<Map<String, Object>> banlanceList) {
        Double result = 0D;
        for (Map<String, Object> map : banlanceList) {
            for (Object o : map.values()) {
                if (o instanceof Double) {
                    Double v = (Double) o;
                    result = result + v;
                }
            }
        }
        return result;
    }

    /**
     * 首页-本月数据
     */
    @AutoLog(value = "统计-营业额")
    @ApiOperation(value = "统计-营业额", notes = "统计-营业额")
    @PostMapping("/turnover")
    public Result<?> data1(
            @RequestBody Map<String, Object> requestMap,
            HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
//        String startDate=null;
//        String endDate=null;
        String startDate = requestMap.get("startDate") == null ? null : String.valueOf(requestMap.get("startDate"));
        String endDate = requestMap.get("endDate") == null ? null : String.valueOf(requestMap.get("endDate"));
        startDate = DateUtils.fixFormat(startDate);
        endDate = DateUtils.fixFormat(endDate);
        Map<String, Object> result = new HashMap<>();
        //总营业收入， 商品销售收入 次卡销售收入 会员/股本充值收入 贵宾卡销售收入
        List<BaseOrder> orderList = baseOrderService.list(new QueryWrapper<BaseOrder>()
                .eq("store_id", storeId)
                .eq("order_status", "1")
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));
        double sumAmount = sumAmountIfNotNull(orderList);
        List<BaseOrderCommodity> list = homePageService.listOrderCommodity(storeId, startDate, endDate);
        double cAmount = 0;
        for (BaseOrderCommodity c : list) {
            String totalPrice = c.getTotalPrice();
            String preferAmount = c.getPreferAmount();
            BigDecimal bigDecimal1 = BigDecimal.ZERO;
            BigDecimal bigDecimal2 = BigDecimal.ZERO;
            if (!StringUtils.isEmpty(totalPrice)) {
                bigDecimal1 = new BigDecimal(totalPrice);
            }
            if (!StringUtils.isEmpty(preferAmount)) {
                bigDecimal2 = new BigDecimal(preferAmount);
            }
            cAmount += bigDecimal1.doubleValue() - bigDecimal2.doubleValue();
        }


        // 贵宾卡
        List<VipOrderRecord> orderRecords4day = vipOrderRecordService.list(new QueryWrapper<VipOrderRecord>().eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));
        Double vipCardAmount = getSum4VipCard(orderRecords4day);
        List<Map<String, Object>> rechargeList = homePageService.listBalanceCount(storeId, "C", startDate, endDate);
        Double balanceAmount = getMapValueSum(rechargeList);
        {
            HashMapEx<String, Object> vmap = new HashMapEx<>();
            vmap.put("commodity", cAmount);
            vmap.put("timeCard", sumAmount - cAmount);
            vmap.put("balance", balanceAmount);
            vmap.put("vipCard", vipCardAmount);
            vmap.put("total", sumAmount + balanceAmount + vipCardAmount);
            result.put("income",  ((HashMapEx<String, Object>) vmap).getMap());
        }
        //会员/股本余额消耗， 总余额消耗，会员余额消耗，股东余额消耗

        List<Map<String, Object>> banlanceList = homePageService.listBalanceCount(storeId, "X", startDate, endDate);
        Double totalBalance = getMapValueSum(banlanceList);

        List<BalanceChangeRecord> memberList = balanceChangeRecordService.list(new QueryWrapper<BalanceChangeRecord>().eq("store_id", storeId).eq("balance_type", "M").eq("change_code", "X")
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));
        double memberBalance = this.fetchBanlanceSum(memberList);

        List<BalanceChangeRecord> sockList = balanceChangeRecordService.list(new QueryWrapper<BalanceChangeRecord>().eq("store_id", storeId).eq("balance_type", "S").eq("change_code", "X")
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));
        double stockBalance = this.fetchBanlanceSum(sockList);
        {
            HashMapEx<String, Object> vmap = new HashMapEx<>();
            vmap.put("total", totalBalance);
            vmap.put("memberBalance", memberBalance);
            vmap.put("stockBalance", stockBalance);
            result.put("balance", vmap.getMap());
        }
        // 次卡消耗数据统计  次卡消耗金额，次卡消耗次数
        List<BaseOrderWriteoffRecord> timeCardsList = baseOrderWriteoffRecordService.list(new QueryWrapper<BaseOrderWriteoffRecord>()
                .eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));
        Double amount = getSum(timeCardsList);
        Double cardAmount = stockBalance + memberBalance;
        {
            HashMapEx<String, Object> vmap = new HashMapEx<>();
            vmap.put("amount", amount);
            vmap.put("count", timeCardsList.size());
            vmap.put("cardAmount", cardAmount);
            result.put("timeCard", vmap.getMap());
        }

        //支付方式统计 总营业收入 扫码支付 现金 微信记账 支付宝记账
        List<BaseOrder> saomaList = baseOrderService.list(new QueryWrapper<BaseOrder>().eq("pay_type", "扫码支付").eq("order_status", "1")
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));

        List<BaseOrder> xianJinList = baseOrderService.list(new QueryWrapper<BaseOrder>().eq("pay_type", "现金").eq("order_status", "1")
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));

        List<BaseOrder> wxList = baseOrderService.list(new QueryWrapper<BaseOrder>().eq("pay_type", "微信记账").eq("order_status", "1")
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));

        List<BaseOrder> alipayList = baseOrderService.list(new QueryWrapper<BaseOrder>().eq("pay_type", "支付宝记账").eq("order_status", "1")
                .ge("date_format(create_time, '%Y-%m-%d')", startDate)
                .le("date_format(create_time, '%Y-%m-%d')", endDate));

        Double saoma = sumAmountIfNotNull(saomaList);
        Double xianjin = sumAmountIfNotNull(xianJinList);
        Double wx = sumAmountIfNotNull(wxList);
        Double alipay = sumAmountIfNotNull(alipayList);
        Double payTotal = saoma + xianjin + wx + alipay;
        {
            HashMapEx<String, Object> vmap
                    = new HashMapEx<>();
            vmap.put("total", sumAmount + balanceAmount + vipCardAmount);
            vmap.put("saoma", saoma);
            vmap.put("xianjin", xianjin);
            vmap.put("wx", wx);
            vmap.put("alipay", alipay);
            vmap.put("payTotal", payTotal);
            result.put("pay", vmap.getMap());
        }

        return Result.ok(result);
    }

    private double fetchBanlanceSum(List<BalanceChangeRecord> memberList) {
        double result = 0.0;
        for (BalanceChangeRecord balanceChangeRecord : memberList) {
            Double amount = balanceChangeRecord.getAmount();
            if (amount != null) {
                result = result + amount.doubleValue();
            }
        }
        return result;
    }

    /**
     * 次卡统计
     * 次卡统计
     */
    @AutoLog(value = "统计-次卡统计")
    @ApiOperation(value = "统计-次卡统计", notes = "统计-次卡统计")
    @PostMapping("/timescard")
    public Result<?> timescard(
            //@RequestBody Map<String, Object> amap ,
            HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        //次卡名称,可用卡数量,剩余次数,剩余金额
        List<BaseOrderProject> list = baseOrderProjectService.list(new QueryWrapper<BaseOrderProject>().eq("store_id", storeId).eq("is_valid","1"));
        HashMap<String, OrderProjectVo> map = new HashMap<>();

        for (BaseOrderProject order : list) {
            String projectName = order.getProjectName();
            OrderProjectVo vo = map.get(projectName);

            if (vo == null) {
                vo = new OrderProjectVo();
                vo.setName(projectName);
                map.put(projectName, vo);
            }
            if (order.getValidateTime() == null) {
                dealOrder(storeId, order, vo);
            } else {
                if (order.getValidateTime().after(new Date())) {
                    dealOrder(storeId, order, vo);
                } else {

                }
            }
        }

        return Result.ok(map.values());
    }

    private void dealOrder(String storeId, BaseOrderProject order, OrderProjectVo vo) {

        String unitPrice = order.getUnitPrice();
        vo.setNum(vo.getNum() + Integer.valueOf(order.getProjectQty()));
        int times = vo.getTimes();
        int itimes = 0;
        List<BaseJobServeItem> list1 = baseJobServeItemService.list(new QueryWrapper<BaseJobServeItem>().eq("store_id", storeId).eq("project_id", order.getProjectId()));
        for (BaseJobServeItem item : list1) {
            times = times + item.getServeNum();
            itimes = itimes + item.getServeNum();

        }

        List<BaseOrderServiceWriteoff> slist = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>().eq("store_id", storeId).eq("order_project_id", order.getId()).eq("status","1"));
        times = times - slist.size();

        if (slist.size() == 0) {
            double remainValue = vo.getRemainValue();

            try {
                remainValue = remainValue + Double.valueOf(unitPrice);
            } catch (Exception e) {

            }
            vo.setRemainValue(remainValue);
        } else {
            double remainValue = vo.getRemainValue();
            try {
                int s = (int) (Double.valueOf(unitPrice) * 100 / itimes * (itimes - slist.size()));
                remainValue = remainValue + s * 0.01;

            } catch (Exception e) {

            }
            vo.setRemainValue(remainValue);
        }
        vo.setTimes(vo.getTimes() +itimes-slist.size());
    }



    /**
     * 次卡项目统计
     */
    @ApiOperation(value = "统计-次卡项目统计", notes = "统计-次卡项目统计")
    @PostMapping("/timescardProject")
    public Result<?> timescardProject(@RequestBody BaseOrderServiceWriteoff2 serviceWriteoff ,HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        serviceWriteoff.setStoreId(storeId);


        //项目名称, 总次数,剩余次数
        List<HashMap> serveList = baseOrderServiceWriteoffService.getServiceCount(serviceWriteoff);



        return Result.OK(serveList);
    }

    /**
     * 次卡项目统计
     */
    @ApiOperation(value = "统计-次卡项目统计", notes = "统计-次卡项目统计")
    @PostMapping("/timescardProject——old")
    public Result<?> timescardProject_old(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        //项目名称, 总次数,剩余次数

        List<BaseOrderProject> list = baseOrderProjectService.list(new QueryWrapper<BaseOrderProject>().eq("store_id", storeId));
        HashMap<String, TimeCardVo> map = new HashMap<>();
        for (BaseOrderProject order : list) {
            String projectName = order.getProjectName();
            TimeCardVo vo = map.get(projectName);

            if (vo == null) {
                vo = new TimeCardVo();
                vo.setName(projectName);
                map.put(projectName, vo);
            }
            if (order.getValidateTime() == null) {
                dealOrder(storeId, order, vo);
            } else {
                if (order.getValidateTime().after(new Date())) {
                    dealOrder(storeId, order, vo);
                } else {

                }
            }
        }

        return Result.ok(map.values());
    }

    private void dealOrder(String storeId, BaseOrderProject order, TimeCardVo vo) {
        String unitPrice = order.getUnitPrice();
        vo.setNum(vo.getNum() + Integer.valueOf(order.getProjectQty()));
        int times = vo.getTimes();
        int itimes = 0;
        List<BaseJobServeItem> list1 = baseJobServeItemService.list(new QueryWrapper<BaseJobServeItem>().eq("store_id", storeId).eq("project_id", order.getProjectId()));
        for (BaseJobServeItem item : list1) {
            times = times + item.getServeNum();
            itimes = itimes + item.getServeNum();

        }
        List<BaseOrderServiceWriteoff> slist = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>().eq("store_id", storeId).eq("order_project_id", order.getId()));
        times = times - slist.size();
        vo.setNum(times);
    }

    /**
     * 次卡余次统计
     */
    @ApiOperation(value = "统计-次卡余次统计", notes = "统计-次卡余次统计")
    @PostMapping("/timescardRemain")
    public Result<?> timescardRemain(
            @RequestBody Map<String, Object> requestMap,
            HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        //查询 会员电话，姓名 次卡名称
        //会员姓名，会员电话，次卡名称， 剩余天数，到期日，剩余次数

        Map<String, Object> result = new HashMap<>();
//        IssuingRecords record = issuingRecordsService.getById(vipid);
////        String storeId = record.getStoreId();
//        vipId = record.getVipId();
        String name = requestMap.get("name") == null ?  "" : String.valueOf(requestMap.get("name"));
        String phone = requestMap.get("phone") == null ?  "" : String.valueOf(requestMap.get("phone"));
        String cardName = requestMap.get("cardName") == null ? "" : String.valueOf(requestMap.get("cardName"));
        Integer pageNo = requestMap.get("pageNo") == null ? Integer.valueOf(1) : Integer.valueOf(requestMap.get("pageNo").toString());
        Integer pageSize = requestMap.get("pageSize") == null ? Integer.valueOf(10) : Integer.valueOf(requestMap.get("pageSize").toString());

        int total = homePageService.countOrderProject(storeId, name, phone, cardName);
        List<Map> maps = homePageService.listOrderProject(storeId, name, phone, cardName, pageNo, pageSize);

        /*
        for (Map vmap : maps) {
            String orderProjectId = vmap.get("orderProjectId").toString();
            Object o = vmap.get("validateTime");
            if (o == null) {
                Object o1 = vmap.get("timeWay");
                if (o1 == null) {
                    BaseOrderProject orderProject = baseOrderProjectService.getById(orderProjectId);
                    String projectId = orderProject.getProjectId();
                    ProjectManagement project = projectManagementService.getById(projectId);
                    //计时方式 1-gm-从购买开始 2- 核销，从第一次消费开始
                    if (project.getTimingWay().equals("1")) {
                        int indate = Integer.valueOf(project.getIndate()).intValue();
                        orderProject.setTimingWay("1");
                        orderProject.setIndate(project.getIndate());
                        Date createTime = orderProject.getCreateTime();
                        long time = createTime.getTime() + (long) indate * 1000 * 3600 * 24;
                        Date date = new Date(time);
                        orderProject.setValidateTime(date);
                        baseOrderProjectService.updateById(orderProject);
                    } else if (project.getTimingWay().equals("2")) {
                        int indate = Integer.valueOf(project.getIndate()).intValue();
                        orderProject.setTimingWay("1");
                        orderProject.setIndate(project.getIndate());
                        List<BaseOrderServiceWriteoff> list = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>().eq("order_id", orderProject.getOrderId()).eq("order_project_id", orderProject.getProjectId()));
                        Date date = new Date();
                        for (BaseOrderServiceWriteoff baseOrderServiceWriteoff : list) {
                            Date createTime = baseOrderServiceWriteoff.getCreateTime();
                            if (createTime != null) {
                                if (createTime.getTime() < date.getTime()) {
                                    date = createTime;
                                }
                            }
                        }
                        long time = date.getTime() + (long) indate * 1000 * 3600 * 24;
                        Date validateTime = new Date(time);
                        orderProject.setValidateTime(validateTime);
                        baseOrderProjectService.updateById(orderProject);
                    }
                }
            } else {
                //remainDays
            }
        }*/


        maps = homePageService.listOrderProject(storeId, name, phone, cardName, pageNo, pageSize);

        for (Map map : maps) {
            String orderProjectId = map.get("orderProjectId").toString();
            BaseOrderProject order = baseOrderProjectService.getById(orderProjectId);
            map.put("projectName", order.getProjectName());

            int times = queryLeftTimesNew(storeId, order);
            map.put("remainTimes", times);
            Object o = map.get("validateTime");
            if (o != null) {
                if (o instanceof Date) {
                    Date validateTime = (Date) o;
                    Date today = new Date();
                    int differDays = DateUtils.getDifferDays(today,validateTime);

                    if (differDays > 0) {
                        map.put("remainDays", differDays);

                    } else {
                        //过期
                        map.put("remainDays", "过期");
                    }
                }
            }

        }


        result.put("current", 1);
        result.put("total", total);
        result.put("records", maps);
        return Result.OK(result);
    }

    private int queryLeftTimes(String storeId, BaseOrderProject order) {
        int times = 0;

        List<BaseJobServeItem> list1 = baseJobServeItemService.list(new QueryWrapper<BaseJobServeItem>().eq("store_id", storeId).eq("project_id", order.getProjectId()));
        for (BaseJobServeItem item : list1) {
            times = times + item.getServeNum();
        }
        List<BaseOrderServiceWriteoff> slist = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>()
                .eq("store_id", storeId)
                .eq("order_project_id", order.getId()));


        times = times - slist.size();
        return times;
    }


    private int queryLeftTimesNew(String storeId, BaseOrderProject order) {
     /*   int times = 0;

        List<BaseJobServeItem> list1 = baseJobServeItemService.list(new QueryWrapper<BaseJobServeItem>().eq("store_id", storeId).eq("project_id", order.getProjectId()));
        for (BaseJobServeItem item : list1) {
            times = times + item.getServeNum();
        }*/
        List<BaseOrderServiceWriteoff> slist = baseOrderServiceWriteoffService
                .list(new QueryWrapper<BaseOrderServiceWriteoff>().eq("store_id", storeId)
                        .eq("order_project_id", order.getId())
                        .eq("status", 0)
                );
        //times = times - slist.size();
        return slist.size();
    }

    /**
     * 余额统计
     */
    @ApiOperation(value = "统计-余额统计", notes = "统计-余额统计")
    @PostMapping("/balance")
    public Result<?> balance(@RequestBody Map<String, Object> requestMap,
                             HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        //查询姓名 电话
        String name = requestMap.get("name") == null ? "" : String.valueOf(requestMap.get("name"));
        String phone = requestMap.get("phone") == null ? "" : String.valueOf(requestMap.get("phone"));
        Integer pageNo = requestMap.get("pageNo") == null ? Integer.valueOf(1) : Integer.valueOf(requestMap.get("pageNo").toString());
        Integer pageSize = requestMap.get("pageSize") == null ? Integer.valueOf(10) : Integer.valueOf(requestMap.get("pageSize").toString());

        // 姓名, 电话, 会员余额,股本余额,总余额
        Map<String, Object> result = new HashMap<>();

        int total = homePageService.countMember(storeId, name, phone);
        List<Map> maps = homePageService.listMember(storeId, name, phone, pageNo, pageSize);
        result.put("current", 1);
        result.put("total", total);
        result.put("records", maps);
        return Result.OK(result);
    }

    private Double getSum4VipCard(List<VipOrderRecord> vipOrderRecords) {
        Double result = 0.0;
        for (VipOrderRecord r : vipOrderRecords) {
            result = result + r.getSellingPrice();
        }
        return result;
    }

    private Double getBanlanceSum(List<BaseOrderWriteoffRecord> timeCardsList) {
        Double result = 0.0;
        for (BaseOrderWriteoffRecord r : timeCardsList) {
            String orderProjectId = r.getOrderProjectId();
            BaseOrderProject orderProject = baseOrderProjectService.getById(orderProjectId);
            if (orderProject != null) {
                String projectId = orderProject.getProjectId();
                String unitPrice = orderProject.getUnitPrice();
                List<BaseJobServeItem> list = baseJobServeItemService.list(new QueryWrapper<BaseJobServeItem>().eq("project_id", projectId));
                if (list.size() == 1) {
                    Integer serveNum = list.get(0).getServeNum();
                    BigDecimal bigDecimal = new BigDecimal(unitPrice);
                    result = result + bigDecimal.divide(BigDecimal.valueOf(serveNum)).doubleValue();
                }
            }
        }
        return result;
    }

    private Double getSum(List<BaseOrderWriteoffRecord> timeCardsList) {
        Double result = 0.0;
        for (BaseOrderWriteoffRecord r : timeCardsList) {
            String orderProjectId = r.getOrderProjectId();
            BaseOrderProject orderProject = baseOrderProjectService.getById(orderProjectId);
            if (orderProject != null) {
                String projectId = orderProject.getProjectId();
                String unitPrice = orderProject.getUnitPrice();
                List<BaseJobServeItem> list = baseJobServeItemService.list(new QueryWrapper<BaseJobServeItem>().eq("project_id", projectId));
                if (list.size() == 1) {
                    Integer serveNum = list.get(0).getServeNum();
                    BigDecimal bigDecimal = new BigDecimal(unitPrice);
                    result = result + bigDecimal.divide(BigDecimal.valueOf(serveNum), 5,RoundingMode.DOWN).doubleValue();
                }
            }
        }
        return result;
    }

}
